package com.hand.wfive.activity.sign

import android.annotation.SuppressLint
import android.graphics.Color
import android.util.Log
import com.alibaba.sdk.android.oss.model.ObjectMetadata
import com.qmuiteam.qmui.widget.QMUITopBarLayout
import com.hand.wfive.App
import com.hand.wfive.R
import com.hand.wfive.ad.AdActivity
import com.hand.wfive.entity.BaseModel
import com.hand.wfive.entity.FileEvent
import com.hand.wfive.entity.FileModel
import com.hand.wfive.entity.ImageVo
import com.hand.wfive.entity.Params
import com.hand.wfive.entity.WordImagesModel
import com.hand.wfive.loginAndVip.ApiConfig
import com.hand.wfive.loginAndVip.LoginConfig
import com.hand.wfive.loginAndVip.UserManager
import com.hand.wfive.loginAndVip.ui.VipActivity
import com.hand.wfive.util.FileUtils
import com.hand.wfive.util.GsonUtil
import com.hand.wfive.util.ImageUtils
import com.hand.wfive.util.click.singleClick
import com.hand.wfive.util.oss.OssCallBack
import com.hand.wfive.util.oss.OssMetadataCallBack
import com.hand.wfive.util.oss.OssRequest
import com.hand.wfive.view.MsgDialog
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.ObservableSource
import io.reactivex.rxjava3.schedulers.Schedulers
import org.greenrobot.eventbus.EventBus
import rxhttp.wrapper.param.RxHttp
import kotlin.concurrent.thread
import kotlin.math.max

abstract class BaseSignActivity : AdActivity() {

    protected var mUpdate = false
    protected lateinit var mFileModel: FileModel
    protected val mPdfPageSize = ArrayList<Pair<Int, Int>>()
    protected val mSaveData = ArrayList<Pair<Boolean, String>>()

    private var mIndex = 0
    private val mFileIds = ArrayList<String>()
    private val mExcludeData = ArrayList<String>()
    private val mFileData = ArrayList<Pair<String, String>>()
    private lateinit var mFileModelCopy: FileModel
    var imageVoList = ArrayList<ImageVo>()//word图片数据
    override fun init() {
        val model = getParcelableExtra<FileModel>(Params.model)
        if (model == null) {
            finish()
            return
        }
        Log.e("init",model.toString())
        mFileModel = model
        mFileModelCopy = mFileModel.copy()

        if (mFileModel.type == Params.fileTypeWord) {
            RxHttp.postForm(ApiConfig.getWordImageData)
                .add("userId", UserManager.getInstance().userId)
                .add("cloudFileId", mFileModel.id)
                .add("appid", LoginConfig.AppId)
                .asClass(WordImagesModel::class.java)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe {
                    if (it.code == 200) {
                        imageVoList = it.`object`.imageVoList as ArrayList<ImageVo>
                        mFileModel.wordToImageId = it.`object`.id
                        onInitData()
                    } else {
                        showErrorTip("加载失败")
                    }

                }

        } else {
            onInitData()
        }

    }


    protected abstract fun onInitData()

    protected fun initTopBar(topBar: QMUITopBarLayout) {
        topBar.addLeftBackImageButton().singleClick { doOnBackPressed() }
        topBar.addRightTextButton("保存", R.id.top_bar_right_text)
            .singleClick { onSave() }
        topBar.updateBottomSeparatorColor(Color.parseColor("#CCCCCC"))
    }

    protected abstract fun onSave()

    /**
     * 保存word图片
     */
    @SuppressLint("CheckResult")
    protected fun saveWord(wordImages: List<ImageVo>, oldWordImages: List<ImageVo>) {
//        if (!UserManager.getInstance().isVip) {
//            MsgDialog(
//                mContext,
//                "保存提醒",
//                "上传Word文件本月已达上限，请购买单独资源包后再试！",
//                negativeBg = R.drawable.btn_dialog_msg_positive_left,
//                positiveBg = R.drawable.btn_dialog_msg_negative_right,
//                negativeText = "确定",
//                positiveText = "取消",
//            ) { position ->
//                if (position == 0) {
//                    VipActivity.show(mContext)
//                }
//
//            }.show()
//        }

        var list = ArrayList<ObservableSource<ImageVo>>()
        for (imageVo in wordImages) {
            val map = Observable.just(imageVo)
                .flatMap { vo ->
                    Observable.create<ImageVo> {
                        var name = mFileModel.fileName.replace(",", "")
                        var fileId = "${UserManager.getInstance().userId}/file/${
                            System.currentTimeMillis()
                        }cover_${name}.jpg"
                        vo.fileId = fileId
                        OssRequest.getInstance()
                            .uploadFile(vo.fileId, vo.path, object : OssCallBack {
                                override fun onSuccess() {
                                    val fileUrl = OssRequest.getInstance().getFileUrl(vo.fileId)
                                    vo.url = fileUrl
                                    it.onNext(vo)
                                    it.onComplete()
                                }

                                override fun onFailure(msg: String?) {
                                    it.onError(Throwable("上传失败"))

                                }
                            })
                    }
                }
            list.add(map)
        }
        Observable.ambArray(*list.toTypedArray())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                for (vo in wordImages) {
                    for (oldVo in oldWordImages) {
                        if (oldVo.slideId == vo.slideId)
                            oldVo.url = vo.url
                    }
                }

                val gsonString = GsonUtil.gsonString(oldWordImages)
                RxHttp.postForm(ApiConfig.saveImageSign)
                    .add("wordToImageId", mFileModel.wordToImageId)
                    .add("images", gsonString)
                    .add("fileId", mFileModel.fileId)
                    .asClass(BaseModel::class.java)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({
                        if (it.code == 200) {
                            dismissTip()
                            EventBus.getDefault().post(FileEvent(Params.fileTypeAll))
                            setResult(RESULT_OK)
                            finish()
                        } else {
                            showNormalTip("保存失败")
                        }

                    }, {
                        showNormalTip("保存失败")
                    })


            }, {
                showNormalTip("保存失败")
            })


    }


    protected fun save() {
        mFileIds.clear()
        mFileData.clear()
        mExcludeData.clear()
        mFileModel.filePath = ""
        var name = mFileModel.fileName.replace(",", "")
        if (name.contains(".")) name = name.substring(0, name.lastIndexOf("."))
        if (mFileModel.type == Params.fileTypeWord) {
            mFileModel.coverFileId = "${UserManager.getInstance().userId}/file/${
                System.currentTimeMillis()
            }cover_${name}.jpg"
            mFileModel.coverPath = mSaveData[0].second


            OssRequest.getInstance().deleteFile(mFileModelCopy.coverFileId, null)
            updateFile()
        } else if (mFileModel.type == Params.fileTypePdf) {
            thread {
                var width = 0
                var height = 0
                val data = ArrayList<String>()
                mPdfPageSize.forEachIndexed { index, pair ->
                    data.add(mSaveData[index].second)
                    width = max(width, pair.first)
                    height = max(height, pair.second)
                }
                mFileModel.filePath = ImageUtils.savePDF(
                    data, App.getContext().cacheTempPath,
                    "${System.currentTimeMillis()}.pdf", width, height
                )
                mFileModel.size = FileUtils.getFileSize(mFileModel.filePath)
                mFileModel.fileId = "${UserManager.getInstance().userId}/file/${
                    System.currentTimeMillis()
                }_${name}.pdf"
                runOnUiThread { saveFile() }
            }
        } else {
            if (mFileModel.fileId.contains(",")) {
                mFileModel.fileId.split(",").forEachIndexed { index, s ->
                    if (mSaveData[index].first) {
                        val fileId = "${UserManager.getInstance().userId}/file/${
                            System.currentTimeMillis()
                        }($index)_${name}.jpg"
                        mFileData.add(Pair(mSaveData[index].second, fileId))
                        mFileIds.add(fileId)
                    } else {
                        mExcludeData.add(s)
                        mFileIds.add(s)
                    }
                }
                mFileModel.fileId = mFileIds[0]
                for (i in 1 until mFileIds.size) {
                    mFileModel.fileId += ",${mFileIds[i]}"
                }
                mIndex = 0
                uploadFile()
            } else {
                mFileModel.filePath = mSaveData[0].second
                mFileModel.size = FileUtils.getFileSize(mFileModel.filePath)
                mFileModel.fileId = "${UserManager.getInstance().userId}/file/${
                    System.currentTimeMillis()
                }_${name}.jpg"
                saveFile()
            }
        }
    }

    private fun uploadFile() {
        val fileData = mFileData[mIndex]
        OssRequest.getInstance().uploadFile(fileData.second, fileData.first, object : OssCallBack {
            override fun onSuccess() {
                mIndex++
                if (mFileData.size > mIndex) uploadFile()
                else {
                    mIndex = 0
                    mFileModel.size = 0
                    calcFileSize()
                }
            }

            override fun onFailure(msg: String) {
                showNormalTip(msg)
            }
        })
    }

    private fun calcFileSize() {
        OssRequest.getInstance().getFileMetadata(mFileIds[mIndex], object : OssMetadataCallBack {
            override fun onSuccess(metadata: ObjectMetadata) {
                mFileModel.size += metadata.contentLength
                mIndex++
                if (mFileIds.size > mIndex) calcFileSize()
                else addFile()
            }

            override fun onFailure(msg: String?) {
                mIndex++
                if (mFileIds.size > mIndex) calcFileSize()
                else addFile()
            }
        })
    }

    private fun addFile() {
        OssRequest.getInstance().delCloudFile(mFileModelCopy, mExcludeData, object : OssCallBack {
            override fun onSuccess() {
                OssRequest.getInstance().addCloudFile(mFileModel, object : OssCallBack {
                    override fun onSuccess() {
                        dismissTip()
                        EventBus.getDefault().post(FileEvent(Params.fileTypeAll))
                        setResult(RESULT_OK)
                        finish()
                    }

                    override fun onFailure(msg: String) {
                        showNormalTip(msg.ifEmpty { "保存失败" })
                    }
                })
            }

            override fun onFailure(msg: String) {
                showNormalTip(msg.ifEmpty { "保存失败" })
            }
        })
    }

    private fun saveFile() {
        OssRequest.getInstance().delCloudFile(mFileModelCopy, mExcludeData, object : OssCallBack {
            override fun onSuccess() {
                updateFile()
            }

            override fun onFailure(msg: String) {
                showNormalTip(msg.ifEmpty { "保存失败" })
            }
        })
    }

    private fun updateFile() {
        OssRequest.getInstance().uploadFile(mFileModel, object : OssCallBack {
            override fun onSuccess() {
                dismissTip()
                EventBus.getDefault().post(FileEvent(Params.fileTypeAll))
                setResult(RESULT_OK)
                finish()
            }

            override fun onFailure(msg: String) {
                showNormalTip(msg.ifEmpty { "保存失败" })
            }
        })
    }

}